﻿using Qy.Common;
using Qy.Models;
using Qy.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Qy.Service
{
    [AppService]
    public class UserPostService
    {
        private readonly UserPostRepository _adminUserPost;
        private readonly ICacheManager _cacheManager;
        private readonly string cacheKey;
        public UserPostService(ICacheManager cacheManager, UserPostRepository adminUserPostRepository)
        {
            _adminUserPost = adminUserPostRepository;
            _cacheManager = cacheManager;
            cacheKey = CacheConst.CACHE_KEY_ADMINPOST;
        }


        public async Task<UserPost> GetInfo(int id)
        {
            List<UserPost> cates = await GetAllAsync();
            return cates.FirstOrDefault(a => a.Id == id);
        }

        /// <summary>
        /// 全部列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserPost>> GetAllAsync()
        {
            List<UserPost> cate = _cacheManager.Get<List<UserPost>>(cacheKey);
            if (cate == null)
            {
                cate = await _adminUserPost.GetAllListAsync("Sort asc");
                _cacheManager.Set(cacheKey, cate, TimeSpan.FromDays(10));
            }
            return cate;
        }


        public async Task<object> InsertAsync(UserPost contentCate)
        {
            try
            {
                var insert = await _adminUserPost.InsertAsync(contentCate);
                if (insert !=null)
                {
                    _cacheManager.Remove(cacheKey);
                    return insert;
                }
                else
                {
                    return null;
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }
        }

        public async Task<int> UpdateAsync(UserPost contentCate)
        {
            try
            {
                if (0<await _adminUserPost.UpdateAsync(contentCate))
                {
                    _cacheManager.Remove(cacheKey);
                    return 1;
                }
                else
                {
                    return 0;
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return 0;
            }
        }

        public async Task<int> DeleteByPriKeyAsync(int id)
        {
            try
            {
                if (0 < await _adminUserPost.DeleteByPriKeyAsync(id))
                {
                    _cacheManager.Remove(cacheKey);
                    return 1;
                }
                else
                {
                    return 0;
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return 0;
            }

            
        }


    }
}
